package com.example.shiro02.config;

import com.example.shiro02.beans.User;
import com.example.shiro02.mapper.PermissionMapper;
import com.example.shiro02.mapper.RoleMapper;
import com.example.shiro02.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @Version 1.0
 * @Author:zlf
 * @Date:2020/11/24 - 14:35
 * @Content:自定义Realm
 * 自定义Realm规范：
 * 1、创建一个类继承AuthorizingRealm类（实现了Realm接口的类）
 * 2、重写doGetAuthorizationInfo和doGetAuthenticationInfo方法
 * 3、重写getName方法,返回当前Realm的一个自定义名称
 */
public class CustomizeRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PermissionMapper permissionMapper;

    //返回当前Realm的一个自定义名称
    @Override
    public String getName() {
        return "customizeRealm";
    }

    //获取授权信息（将当前用户的角色及权限信息查询出来）
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前用户的用户名
        String  username = (String)principalCollection.iterator().next();
        //根据用户名查询当前用户的角色列表
        Set<String> roleNames = roleMapper.queryRoleNameByUsername(username);
        //根据用户名查询当前用户的权限列表
        Set<String> ps = permissionMapper.queryPermissionsByUsername(username);
        System.out.println("-------------------查询角色及权限信息");
        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
        info.setRoles(roleNames);
        info.setStringPermissions(ps);
        return info;
    }
    //获取认证的安全数据（从数据库查询的用户的正确数据）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //参数authenticationToken就是传递的 subject.login(token)
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        //重Token中获取用户名
        String username=token.getUsername();
        //根据用户名，从数据库查询当前用户的安全数据
        User user = userMapper.queryUserByUsername(username);
     /*   if(user==null){
            return null;
        }*/
       /* AuthenticationInfo info = new SimpleAuthenticationInfo(
                user.getUserName(),//当前用户用户名
                user.getUserPwd(),//当前用户密码
                getName());//当前Realm*/
       //如果数据库中用户的密码是加盐的情况
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                user.getUserName(),//当前用户用户名
                user.getUserPwd(),//当前用户密码
                ByteSource.Util.bytes(user.getPwdSalt()),
                getName());
        return info;
    }
}
